package com.zlq.controller;



import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.zlq.pojo.User;
import com.zlq.service.impl.UserServiceImpl;
import org.apache.tomcat.util.http.fileupload.ByteArrayOutputStream;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.util.List;

@Controller
public class toLoginController {
    @Resource
    private UserServiceImpl userService;

    /**
     * 跳转登录页面
     */
    @RequestMapping("/toLogin")
    public String toLogin() {
        return "login";
    }

    //图片验证码
    @Resource
    private DefaultKaptcha defaultKaptcha;

    /**
     * 验证码
     */
    @RequestMapping("/defaultKaptcha")
    public void defaultKaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        byte[] captcha = null;
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        try {
            // 将生成的验证码保存在session中
            String createText = defaultKaptcha.createText();
            request.getSession().setAttribute("rightCode", createText);
            BufferedImage bi = defaultKaptcha.createImage(createText);
            ImageIO.write(bi, "jpg", out);
        } catch (Exception e) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        captcha = out.toByteArray();
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        ServletOutputStream sout = response.getOutputStream();
        sout.write(captcha);
        sout.flush();
        sout.close();
    }

    /**
     * 登录用户名、密码和验证码验证
     */
    @RequestMapping("/login")
    public String login(User user, String code, Model model, HttpSession session) throws Exception {
        String name = user.getName();
        System.out.println("输入用户名为"+name);
        String password = user.getPassword();
        System.out.println("输入密码为"+password);
        System.out.println("输入验证码为"+code);
        String scode = (String) session.getAttribute("rightCode");
        System.out.println("底层验证码"+scode);
        if (code != null) {
            if (scode.equals(code)) {
                if (name != null && !name.equals("")) {
                    List<User> users = userService.selectByName(name);
                    System.out.println("查数据库为"+users);
                    for (User username : users) {
                        if (username.getName().equals(name) && username.getPassword().equals(password)) {
                            session.setAttribute("name",name);
                            return "index";
                        }
                    }
                } else {
                    model.addAttribute("msg","用户名错误");
                    return "login";
                }
            } else {
                model.addAttribute("msg","验证码错误");
                return "login";
            }
        } else {
            model.addAttribute("msg","请输入验证码");
            return "login";
        }
        return null;
    }

    /**
     * 跳转注册页面
     */
    @RequestMapping("/toRegister")
    public String toRegister() {
        return "register";
    }

    /**
     * 用户注册后保存信息到数据库
     */
    @RequestMapping("/register")
    public String register(User user, String code,HttpSession session,Model model) {
        String token = (String) session.getAttribute("rightCode");
        String name = user.getName();
        String password = user.getPassword();
        if ((!name.isEmpty() || !name.equals("")) && (!password.isEmpty() || !password.equals("")) && (code != null || token.equals(code))) {
            model.addAttribute("name", name);
            userService.save(user);
            return "login";
        } else {
            model.addAttribute("msg","信息错误");
            return "register";
        }
    }

    /**
            * 跳转添加页面
     */
    @RequestMapping("/saveUser")
    public String saveUser() {
        return "saveUser";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session){
        //移除Session
        session.invalidate();
        return "redirect:/login.html";
    }


}
